<template>
  <section>
    <!--工具条:高级查询和新增-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">上架</el-button>
          <el-button type="primary" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--分页列表-->
    <!--
      :data="pets" - 列表数据
      highlight-current-row - 当前行高亮
      v-loading="listLoading" - 加载框
      @selection-change="selsChange" - 批量操作要使用的方法
    -->
    <el-table v-loading="listLoading" :data="pets" highlight-current-row style="width: 100%;"
              @selection-change="selsChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column label="宠物名称" prop="name" width="80">
      </el-table-column>
      <el-table-column label="成本价" prop="costprice" width="100">
      </el-table-column>
      <el-table-column label="售价" prop="saleprice" width="100">
      </el-table-column>
      <el-table-column label="宠物类型" prop="petType.name" width="80">
      </el-table-column>
      <el-table-column label="状态" prop="state" sortable width="100">
        <template scope="scope">
          <span v-if="scope.row.state==1" style="color: lawngreen">上架</span>
          <span v-else style="color: red">下架</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createtime" width="120">
      </el-table-column>
      <el-table-column label="上架时间" prop="onsaletime" width="120">
      </el-table-column>
      <el-table-column label="下架时间" prop="offsaletime" width="120">
      </el-table-column>
      <el-table-column label="所在店铺" prop="shop.name" width="80">
      </el-table-column>
      <el-table-column label="领养人" prop="user.username" width="80">
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条:批量删除和分页栏-->
    <!--
          :disabled="this.sels.length===0"
          如果模型数据中this.sels长度为0，就禁用，否则就启用
        -->
    <el-col :span="24" class="toolbar">
      <el-button :disabled="this.sels.length===0" type="danger" @click="batchRemove">批量删除</el-button>
      <el-pagination :current-page="currentPage" :page-size="pageSize"
                     :total="totals" layout="prev, pager, next" style="float:right;" @current-change="handleCurrentChange">
      </el-pagination>
    </el-col>

    <!--修改和添加对话框-->
    <!--
          :title="title"  - 标题
          :visible.sync="saveFormVisible" - 控制对话框是否显示
          :close-on-click-modal="false" - 点击框外的区域不关闭
            :model="saveForm" - 表单数据是一个对象
            label-width="80px" - 标签的宽度
            :rules="saveFormRules" - 表单项验证
            ref="saveForm" - 给当前表单取一个名称 - 用来做表单验证
        -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="saveFormVisible">
      <el-form ref="saveForm" :model="saveForm" :rules="saveFormRules" label-width="80px">
        <!--prop="name"需要验证就加上这个属性，不需要验证就不加-->
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
          <el-form-item label="宠物类型" prop="typeId">
            <el-cascader  v-model="saveForm.typeId"
                          :options="petTypeTree"
                          :props="{
                checkStrictly: true,
                label: 'name',
                value: 'id',
              }"clearable>
            </el-cascader>
          </el-form-item>
        <el-form-item label="所在店铺">
          <el-select v-model="saveForm.shopId" placeholder="请选择">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
          <el-form-item label="资源" prop="resources">
            <el-upload class="upload-demo"
                       action="http://localhost:8080/fastDfs"
                       :on-remove="handleRemove"
                       :on-success="handleSuccess"
                       :file-list="fileList"
                       list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>

        </el-form-item>
        <el-form-item label="简介">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知">
          <quill-editor  v-model="saveForm.petDetail.adoptNotice" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>
      <!--
            @click.native="saveSubmit" - 点击提交的时候调用saveSubmit方法
            :loading="saveLoading" - 提交的加载加载框
          -->
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button :loading="saveLoading" type="primary" @click.native="saveSubmit">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>
<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  //模型数据
  data() {
    return {
      quillOption: quillConfig,
      //列表显示图片的前缀
      imgPrefix: "http://123.207.27.208",
      //1.分页查询相关数据
      pets: [],    //分页数据
      listLoading: false, //加载框
      totals: 0,          //总条数
      currentPage: 1,     //当前页
      pageSize: 5,        //每页显示的条数

      //2.高级查询相关数据
      keyword:'',

      //3.删除的相关数据[没有数据]

      //4.批量删除的相关数据
      sels: [],//列表选中列

      //5.添加和修改的相关数据
      title:'',
      saveFormVisible: false,//控制对话框是否显示-默认不显示
      saveLoading: false, //加载对话框
      saveFormRules: {
        //表单中的prop属性
        name: [
          {required: true, message: '请输入宠物名称', trigger: 'blur'}
        ],
      },
      //编辑界面数据
      saveForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      },

      //6.下拉列表的数据
      shops: [],

      //7.模型数据deptTree,部门树
      petTypeTree:[],
      //文件上传的模型数据
      fileList:[]
    }

  },
  //自定义的方法
  methods: {
    //1.分页查询
    //获取用户列表
    getPets() {
      //组装参数
      let para = {
        //分页参数
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        //高级查询的参数
        keyword:this.keyword
      };
      //显示加载框
      this.listLoading = true;
      this.$http.post("/pet", para).then(res => {
        //赋值总数量 - 计算分页栏
        this.totals = res.data.totals;
        this.pets = res.data.data;
        //隐藏加载框
        this.listLoading = false;
      }).catch(res => {
        this.$message.error("网络繁忙,请稍后重试!!!")
      })
    },

    //2.点击分页的方法
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPets();
    },

    //3.高级查询的方法
    keywordQuery(){
      //防止高级查询的时候出现空的现象(当前页是第5页,查询2的时候,数据为空)
      this.currentPage=1;
      this.getPets();
    },

    //4.删除单个
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {//确认框:点击确定走then的逻辑
        //开启加载框
        this.listLoading = true;
        this.$http.delete("/pet/"+row.id).then(res=>{
          //关闭加载框
          this.listLoading = false;
          if(res.data.success){
            this.$message.success("删除成功");
            //删除的优化:计算总页数,Math.celi向上取整,总条数除以每页显示的条数就等于总页数
            var totalPage = Math.ceil(this.totals/this.pageSize);
            //删除最后一页的最后一条数据,而且不能是第一页的时候,让当前页=当前页-1
            //判断条件:1.当前页等于总页数 2.总条数-1模每页显示的条数=0 3.当前页不等于1
            if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage = this.currentPage-1;
            }
            this.getPets();
          }else {
            this.$message.error("系统错误,请稍后重试![500]")
          }
        }).catch(res=>{
          this.$message.error("系统错误,请稍后重试![404,400,服务器没开]")
        })
      }).catch(() => {
      });
    },


    //5.选项改变的时候就会触发
    selsChange:function(sels){
      this.sels = sels;
    },

    //6.批量删除的逻辑
    //批量删除
    batchRemove: function () {
      //获取数组中的每一个对象的id_数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;//显示列表的加载框
        this.$http.patch("/pet",ids).then(res=>{
          this.listLoading = false;//关闭列表的加载框
          if(res.data.success){
            this.$message.success("删除成功");
            //使用批量删除过后返回第一页
            this.currentPage = 1;
            this.getPets();
          }else {
            this.$message.error("系统错误,请稍后重试![500]")
          }
        }).catch(res=>{
          this.$message.error("系统异常，请稍后重试!【服务器没开,404,400】")
        })
      }).catch(() => {//点击取消
      });
    },


    //7.点击修改按钮弹出对话框
    //7.点击修改按钮弹出对话框
    handleSave: function (index, row) {
      //动态修改标题
      this.title = "修改";
      //回显数据
      //克隆对象防止列表中的数据也发生改变
      this.saveForm = Object.assign({}, row);//按照属性同名原则进行赋值
      //显示对话框
      this.saveFormVisible = true;

      //点击修改将resources中的数据 - 装到fileList中
      this.fileList=[];//先清空 - 再添加最新的所有该宠物图片
      if(this.saveForm.resources){
        let arr = this.saveForm.resources.split(",");//[xx,xx,xx]
        for(var i = 0;i<arr.length;i++){
          this.fileList.push({"url":"http://123.207.27.208"+arr[i]});
        }
      }

      this.getShops();
      this.getPetTypeTree();
    },
    //8.点击添加按钮弹出对话框
    handleAdd: function () {
      //动态修改标题
      this.title = "添加";
      this.saveForm = {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: '',
        }
      };
      this.getPetTypeTree();
      this.getShops();
      //清空fileList
      this.fileList=[];
      //显示对话框
      this.saveFormVisible = true;
    },

    //9.点击提交数据
    saveSubmit: function () {
      //将所有ref的表单【ref="saveForm"】,validate-验证
      //valid-只要有一个表单项验证不通过返回false,只有所有表单项验证通过,才返回true
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //显示提交的加载框
            this.saveLoading = true;
            //para对象
            let para = Object.assign({}, this.saveForm);
            //如果为null,[] 就赋值为null，后端Long可以接收为null
            if(para.typeId == null || para.typeId.length==0){
              para.typeId = null;
              //如果有值：[ 1 ],[ 2, 5, 6 ]
            }else if(para.typeId.length){//没有选过就是之前的部门的话，result.length为undefined，判断为false
              para.typeId = para.typeId[para.typeId.length-1]
            }
            //发送请求
            this.$http.put("/pet", para).then(res => {
              //关闭提交的加载框
              this.saveLoading = false;
              //关闭对话框
              this.saveFormVisible = false;
              if (res.data.success) {
                this.$message.success("操作成功");
                this.getPets();
              } else {
                this.$message.error("系统异常，请稍后重试!【500】");
              }
            }).catch(res => {
              this.$message.error("系统异常，请稍后重试!【服务器没开,404,400,405】")
            })
          });
        }
      });
    },


    getShops(){
      this.$http.get("/shop").then(res=>{
        this.shops=res.data;
      })
    },

    getPetTypeTree(){
      this.$http.get("/petType/petTypeTree").then(res=>{
        this.petTypeTree=res.data;
      })
    },

    //文件上传的业务逻辑
    handleSuccess(response, file, fileList){

      //处理resources
      if(this.saveForm.resources){
        this.saveForm.resources=this.saveForm.resources+","+response.obj;
      }else{
        this.saveForm.resources=response.obj;
      }
      //处理fileList
      //先清空
      this.fileList=[];//[{xx},{yy}]
      if(this.saveForm.resources){
        let arr = this.saveForm.resources.split(",");//[xx,yy]
        for(var i=0;i<arr.length;i++){
          this.fileList.push({"url":"http://123.207.27.208"+arr[i]});
        }
      }
    },

    //文件删除的业务逻辑
    handleRemove(file, fileList) {
      console.log(file)
      //调用删除接口删除fastDfs中的数据
      let url = file.url;//"http://123.207.27.208/group1/M00/03/C1/CgAIC2PvQQGAFnniAAFEtmGYbPs057.jpg"
      //截取后面部分
      let path = url.substring(url.indexOf("/group"));
      this.$http.delete("/fastDfs?path="+path).then(res=>{
        if(res.data.success){
          this.$message.success("删除成功");
        }else {
          this.$message.error("删除失败");
        }
      })


      //处理resources
      if(this.saveForm.resources){
        //如果有值，就根据逗号分割，得到数组 ，便利
        let arr = this.saveForm.resources.split(",");//[xx,zz,yy]
        for (var i = 0;i<arr.length;i++){
          //当前端删除时获取的路径等于数据库中的路径时
          if(path==arr[i]){
            //删除这个数据，下标  ， 删除几个
            arr.splice(i,1);//[xx,yy]
            break;
          }
        }//用逗号把新的数据拼接起来，跟split相反
        this.saveForm.resources=arr.join(",");//xx,yy
      }



      //处理fileList
      //先清空
      this.fileList=[];//[{xx},{yy}]
      if(this.saveForm.resources){
        let arr = this.saveForm.resources.split(",");//[xx,yy]
        for(var i=0;i<arr.length;i++){
          this.fileList.push({"url":"http://123.207.27.208"+arr[i]});
        }
      }
    },

    //上架的逻辑
    onsale(){
      //获取数组中的每一个对象的id_数组
      var ids = this.sels.map(item => item.id);
      if(!this.sels||this.sels.length<1){
        return;
      }
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.post("/pet/onsale",ids).then(res=>{
          if(res.data.success){
            this.$message.success("上架成功");
            this.getPets();
          }else {
            this.$message.error(res.data.msg)
          }
        }).catch(res=>{
          this.$message.error("系统异常，请稍后重试!【服务器没开,404,400】")
        })
      }).catch(() => {//点击取消
      });
    },

    //下架的逻辑
    offsale(){
      //获取数组中的每一个对象的id_数组
      var ids = this.sels.map(item => item.id);
      if(!this.sels||this.sels.length<1){
        return;
      }
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.post("/pet/offsale",ids).then(res=>{
          if(res.data.success){
            this.$message.success("下架成功");
            //使用批量删除过后返回第一页
            this.getPets();
          }else {
            this.$message.error("系统错误,请稍后重试![500]")
          }
        }).catch(res=>{
          this.$message.error("系统异常，请稍后重试!【服务器没开,404,400】")
        })
      }).catch(() => {//点击取消
      });
    },
  },
  //页面加载事件
  mounted() {
    this.getPets();
  }
}

</script>

<style scoped>

</style>